import React, { Component, Fragment } from 'react';
import { Button, Spin, Form } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileReader from '@/components/FileReader';
import AntdFormItem from '@/components/AntdFormItem';
import AdConfirm from '@/components/AdConfirm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import {
  formItemFragement,
  queryDict,
  filterAddFile,
  filterDeteteFile,
  queryPerson,
} from '@/utils/common';
import PartsOfferInfo from './PartsOfferInfo';
import { allDictList } from '@/utils/constans';
import { allDispatchType, allUrl, formate, routeUrl, codes } from './utils';

@connect(({ partsOffer, component, loading }) => ({
  partsOfferDetail: partsOffer.partsOfferDetail,
  partsOfferInfo: partsOffer.partsOfferInfo,
  formValues: partsOffer.formValues,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.detail],
}))
@Form.create()
export default class PartsOfferOperate extends Component {
  state = {
    detailId: '',
    selectedRows: [],
    disabled: false,
  };
  fileList = [];
  deleteInfoIds = [];

  componentWillMount() {
    const allDict = [allDictList.partsSupplier];
    queryDict({ props: this.props, allDict });
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
      partsOfferDetail,
    } = this.props;
    if (!id) return;
    this.handleStateChange([{ detailId: id }]);
    this.selectPartsOfferDetail(id);
  }

  selectPartsOfferDetail = id => {
    const { dispatch, form } = this.props;
    dispatch({
      type: allDispatchType.detail,
      payload: { id },
      callback: data => {
        this.setTabName({
          id,
          name: data.offerNo,
          isReplaceTab: false,
        });
        this.fileList = data.fileList;
        form.setFieldsValue({ fileTokens: data.fileList });
      },
    });
  };

  headerOperate = () => {
    const { detailId, disabled } = this.state;
    return disabled ? (
      <AdButton
        type="primary"
        onClick={() => {
          this.setState(preState => ({
            disabled: !preState.disabled,
          }));
        }}
        text="编辑"
        code={detailId ? codes.edit : codes.add}
      />
    ) : (
      <Button.Group>
        <AdButton
          text="保存"
          type="primary"
          code={detailId ? codes.edit : codes.add}
          onClick={this.saveInfo}
        />
        {detailId && (
          <AdButton
            onClick={() => {
              this.setState(preState => ({
                disabled: !preState.disabled,
              }));
            }}
            text="取消"
            code={detailId ? codes.edit : codes.add}
          />
        )}
      </Button.Group>
    );
  };

  /**
   * 获取表单内容
   */
  saveInfo = () => {
    const { form, partsOfferDetail, partsOfferInfo } = this.props;
    const { detailId } = this.state;
    const partsOfferInfoForm = this.child.props.form;
    partsOfferInfoForm.validateFieldsAndScroll(errors => {
      if (errors) return;
      let relationVOS = [];
      if (detailId) {
        relationVOS = partsOfferInfo[detailId].list.map(item => {
          if (item.id.includes('isNew')) {
            const { id, ...rest } = item;
            return rest;
          }
          return item;
        });
      } else {
        relationVOS = partsOfferInfo[''].list;
      }
      form.validateFieldsAndScroll((errors, values) => {
        if (errors) return;
        const { effeTime, fileTokens, offerDate, ...params } = values;
        if (effeTime&&effeTime.length>0) {
          params.effeTimeBegin = moment(effeTime[0]).format(formate);
          params.effeTimeEnd = moment(effeTime[1]).format(formate);
        }else{
          params.effeTimeBegin=''
          params.effeTimeEnd=''
        }
        if (offerDate) {
          params.offerDate = moment(offerDate).format(formate);
        }
        params.fileTokens = filterAddFile(fileTokens);
        params.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
        params.id = detailId;
        params.deleteRelationIds = this.deleteInfoIds;
        params.relationVOS = relationVOS;
        this.saveOrSaveInfo(params);
      });
    });
  };

  /**
   * 保存数据
   */
  saveOrSaveInfo = params => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.save,
      payload: params,
      callback: data => {
        if (!data) return;
        this.setState(preState => ({
          disabled: !preState.disabled,
        }));
        if (params.id) {
          this.selectPartsOfferDetail(params.id);
          this.selectPartsOfferInfo(params.id);
        } else {
          this.setTabName(
            {
              isReplaceTab: true,
            },
            data
          );
        }
        this.selectPartsOfferList();
      },
    });
  };

  selectPartsOfferList = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.list,
      payload: payload || {},
      callback: data => {
        if (!data) return;
        queryPerson({ data, props: this.props, url: allUrl.userList });
      },
    });
  };

  addInfo = e => {
    e.stopPropagation();
    this.child.addInfo();
  };

  saveAllValue = payload => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.value,
      payload: payload || {},
    });
  };

  removeInfo = e => {
    e.stopPropagation();
    const { detailId, selectedRows } = this.state;
    const { partsOfferInfo } = this.props;
    const deleteIds = selectedRows.map(v => v.id);
    this.deleteInfoIds = selectedRows.filter(item => !item.id.includes('isNew')).map(v => v.id);
    const newData = partsOfferInfo[detailId].list.filter(item => !deleteIds.includes(item.id));
    this.saveAllValue({ partsOfferInfo: { [detailId]: { list: newData } } });
    this.handleStateChange([{ selectedRows: [] }]);
  };

  setTabName = (payload, id) => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.setTabsName,
      payload,
      callback: data => {
        if (!data || !payload.isReplaceTab) return;
        router.push(`${routeUrl.edit}/${id}`);
      },
    });
  };

  selectPartsOfferInfo = id => {
    const { dispatch } = this.props;
    dispatch({
      type: allDispatchType.info,
      payload: { id },
    });
  };

  onRef = ref => {
    this.child = ref;
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      partsOfferDetail,
      dictObject,
    } = this.props;
    const { detailId, selectedRows, disabled } = this.state;
    const detail = partsOfferDetail[detailId];
    const { offerNo, mdsCompanyId, offerDate, effeTimeBegin, effeTimeEnd } = detail || {};

    const commonParams = {
      getFieldDecorator,
    };

    const editPageParams = {
      title: offerNo || '新增配件报价',
      headerOperate: this.headerOperate(),
      panelValue: [
        { key: '基础信息' },
        {
          key: '明细',
          extra: (
            <>
              <AdButton
                onClick={e => {
                  this.removeInfo(e);
                }}
                ghost
                code={codes.addInfo}
                disabled={disabled || selectedRows.length === 0}
                text="删除"
                type="danger"
              />
              <AdButton
                type="primary"
                code={codes.deleteInfo}
                disabled={disabled}
                onClick={e => {
                  this.addInfo(e);
                }}
                style={{ marginLeft: 8 }}
                text="新增"
              />
            </>
          ),
        },
      ],
    };

    const formItem = [
      [
        <AntdFormItem
          label="单号"
          code="offerNo"
          initialValue={offerNo || '保存后自动生成'}
          {...commonParams}
        >
          <AntdInput disabled={true} />
        </AntdFormItem>,
        <AntdFormItem
          label="供应商名称"
          initialValue={mdsCompanyId}
          code="mdsCompanyId"
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            data={dictObject[allDictList.partsSupplier]}
            payload={{ code: allDictList.partsSupplier }}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="报价日期"
          code="offerDate"
          initialValue={offerDate ? moment(offerDate) : undefined}
          {...commonParams}
        >
          <AntdDatePicker disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label="有效期"
          initialValue={effeTimeBegin ? [moment(effeTimeBegin), moment(effeTimeEnd)] : undefined}
          code="effeTime"
          {...commonParams}
        >
          <AntdDatePicker mode="range" disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem label="附件" code="fileTokens" {...commonParams}>
          <FileReader urlType="tms" disabled={disabled} />
        </AntdFormItem>,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={detailId ? loading : false}>
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
        </Spin>
        <Fragment>
          <PartsOfferInfo
            onRef={this.onRef}
            selectedRows={selectedRows}
            disabled={disabled}
            onSelectRow={selectedRows => this.handleStateChange([{ selectedRows }])}
          />
        </Fragment>
      </EditPage>
    );
  }
}
